/**
 * 知识库 Pinia Store
 * 
 * 管理知识库相关的状态
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as kbApi from '@/services/knowledge-base'

export const useKnowledgeBaseStore = defineStore('knowledge-base', () => {
  // ==================== State ====================
  
  // 文档列表
  const documents = ref([])
  
  // 当前选中的文档
  const currentDocument = ref(null)
  
  // 统计信息
  const stats = ref(null)
  
  // 加载状态
  const loading = ref(false)
  
  // 错误信息
  const error = ref(null)
  
  // 搜索查询
  const searchQuery = ref('')
  
  // 搜索结果
  const searchResults = ref([])
  
  // 搜索加载状态
  const searching = ref(false)
  
  // ==================== Computed ====================
  
  // 文档总数
  const documentCount = computed(() => documents.value.length)
  
  // 按类型分组的文档
  const documentsByType = computed(() => {
    const grouped = {}
    documents.value.forEach(doc => {
      const type = doc.doc_type || 'other'
      if (!grouped[type]) {
        grouped[type] = []
      }
      grouped[type].push(doc)
    })
    return grouped
  })
  
  // 文档类型分布
  const typeDistribution = computed(() => {
    return Object.entries(documentsByType.value).map(([type, docs]) => ({
      type,
      count: docs.length
    }))
  })
  
  // ==================== Actions ====================
  
  /**
   * 添加文档到知识库
   */
  const addDocuments = async (docs) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await kbApi.addDocuments(docs)
      
      // 刷新文档列表
      await fetchDocuments()
      
      // 刷新统计信息
      await fetchStats()
      
      return response
    } catch (err) {
      error.value = err.message || '添加文档失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 获取文档列表
   */
  const fetchDocuments = async (params = {}) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await kbApi.getDocuments(params)
      documents.value = response.data || []
      return response
    } catch (err) {
      error.value = err.message || '获取文档列表失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 获取单个文档详情
   */
  const fetchDocumentDetail = async (docId) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await kbApi.getDocumentDetail(docId)
      currentDocument.value = response.data
      return response
    } catch (err) {
      error.value = err.message || '获取文档详情失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 更新文档
   */
  const updateDocument = async (docId, data) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await kbApi.updateDocument(docId, data)
      
      // 更新本地列表
      const index = documents.value.findIndex(d => d.id === docId)
      if (index >= 0) {
        documents.value[index] = { ...documents.value[index], ...data }
      }
      
      return response
    } catch (err) {
      error.value = err.message || '更新文档失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 删除单个文档
   */
  const deleteDocument = async (docId) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await kbApi.deleteDocument(docId)
      
      // 从本地列表删除
      documents.value = documents.value.filter(d => d.id !== docId)
      
      // 刷新统计
      await fetchStats()
      
      return response
    } catch (err) {
      error.value = err.message || '删除文档失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 批量删除文档
   */
  const deleteDocumentsBatch = async (docIds) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await kbApi.deleteDocuments(docIds)
      
      // 从本地列表删除
      documents.value = documents.value.filter(d => !docIds.includes(d.id))
      
      // 刷新统计
      await fetchStats()
      
      return response
    } catch (err) {
      error.value = err.message || '批量删除文档失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 搜索知识库
   */
  const search = async (query, maxResults = 5) => {
    searching.value = true
    error.value = null
    
    try {
      searchQuery.value = query
      const response = await kbApi.searchKnowledgeBase(query, maxResults)
      searchResults.value = response.data?.results || []
      return response
    } catch (err) {
      error.value = err.message || '搜索失败'
      searchResults.value = []
      throw err
    } finally {
      searching.value = false
    }
  }
  
  /**
   * 清空搜索
   */
  const clearSearch = () => {
    searchQuery.value = ''
    searchResults.value = []
  }
  
  /**
   * 获取统计信息
   */
  const fetchStats = async () => {
    try {
      const response = await kbApi.getKnowledgeBaseStats()
      stats.value = response.data
      return response
    } catch (err) {
      console.error('获取统计信息失败:', err)
      // 不设置 error，因为这个操作不影响用户操作
    }
  }
  
  /**
   * 上传文件
   */
  const uploadFile = async (file, docType, metadata = {}, source = null) => {
    loading.value = true
    error.value = null
    
    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('doc_type', docType)
      if (source) {
        formData.append('source', source)
      }
      if (metadata && Object.keys(metadata).length > 0) {
        formData.append('metadata', JSON.stringify(metadata))
      }
      
      const response = await kbApi.uploadFile(formData)
      
      // 刷新列表
      await fetchDocuments()
      await fetchStats()
      
      return response
    } catch (err) {
      error.value = err.message || '文件上传失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 导入文档
   */
  const importDocuments = async (file) => {
    loading.value = true
    error.value = null
    
    try {
      const formData = new FormData()
      formData.append('file', file)
      
      const response = await kbApi.importDocuments(formData)
      
      // 刷新列表
      await fetchDocuments()
      await fetchStats()
      
      return response
    } catch (err) {
      error.value = err.message || '导入文档失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 导出知识库
   */
  const exportKB = async () => {
    loading.value = true
    error.value = null
    
    try {
      const response = await kbApi.exportKnowledgeBase()
      
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `knowledge-base-${Date.now()}.json`)
      document.body.appendChild(link)
      link.click()
      link.parentNode.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      return response
    } catch (err) {
      error.value = err.message || '导出知识库失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 清空错误信息
   */
  const clearError = () => {
    error.value = null
  }
  
  /**
   * 重置状态
   */
  const reset = () => {
    documents.value = []
    currentDocument.value = null
    stats.value = null
    loading.value = false
    error.value = null
    searchQuery.value = ''
    searchResults.value = []
    searching.value = false
  }
  
  return {
    // State
    documents,
    currentDocument,
    stats,
    loading,
    error,
    searchQuery,
    searchResults,
    searching,
    
    // Computed
    documentCount,
    documentsByType,
    typeDistribution,
    
    // Actions
    addDocuments,
    fetchDocuments,
    fetchDocumentDetail,
    updateDocument,
    deleteDocument,
    deleteDocumentsBatch,
    search,
    clearSearch,
    fetchStats,
    uploadFile,
    importDocuments,
    exportKB,
    clearError,
    reset
  }
})

export default useKnowledgeBaseStore






